﻿using System;
using System.Windows;
using Ping.App;
using Ping.App.Jobs;
using Ping.Core;

namespace Ping.Client.Pages
{
	public partial class DnsResultPage
	{
		private Job _currentJob;

		public DnsResultPage()
		{
			InitializeComponent();
			Loaded += PageLoaded;
		}

		private void PageLoaded(object sender, RoutedEventArgs e)
		{
			lb_select.Items.Clear();

			if (StateService.State.DnsResult is DnsResult)
			{
				var tmp = (DnsResult) StateService.State.DnsResult;
				foreach (IpAddress address in tmp.Addresses)
				{
					lb_select.Items.Add(address);
				}

				lb_select.SelectedIndex = 0;
			}

			UpdatePage();
		}

		private void PingClick(object sender, RoutedEventArgs e)
		{
			if (_currentJob != null)
				throw new InvalidOperationException();

			string address = lb_select.SelectedItem.ToString();
			var request = new TracerouteRequest {Destination = IpAddress.Parse(address)};
			_currentJob = StateService.State.Scheduler.GetJob(request);
			_currentJob.Perform(request, TraceFinished);

			UpdatePage();
		}

		private void TraceFinished(Result result, Exception e)
		{
			Dispatcher.BeginInvoke(() =>
			                       	{
			                       		_currentJob = null;
			                       		StateService.State.TraceResult = null;

			                       		if (result is TracerouteResult)
			                       		{
			                       			StateService.State.TraceResult = result;
			                       			NavigationService.Navigate(new Uri("/Pages/TraceResultPage.xaml", UriKind.Relative));
			                       		}
			                       		else if (result == null)
			                       		{
			                       			MessageBox.Show("The application server didn't respond", "Error", MessageBoxButton.OK);
			                       		}
			                       		else if (result is OperationResult)
			                       		{
			                       			var status = (OperationResult) result;
			                       			MessageBox.Show(
			                       				string.Format("The application server responded with: {0}", status.Status), "Error",
			                       				MessageBoxButton.OK);
			                       		}
			                       		else
			                       		{
			                       			MessageBox.Show("The application server's response could not be handled", "Error",
			                       			                MessageBoxButton.OK);
			                       		}

										UpdatePage();
			                       	});
		}

		private void UpdatePage()
		{
			if (_currentJob != null)
			{
				doPing.IsEnabled = false;
				loading.Visibility = Visibility.Visible;
			}
			else
			{
				doPing.IsEnabled = true;
				loading.Visibility = Visibility.Collapsed;
			}
		}
	}
}